const addBtn = document.getElementById('add');

const notes = JSON.parse(localStorage.getItem('notes'));

if (notes) {
    notes.forEach(function(note) {
        addNewNote(note);
    });
}

addBtn.addEventListener('click', function() {
    addNewNote();
});

function addNewNote(text = '') {
    const note = document.createElement('div');
    note.classList.add('note');

    note.innerHTML = `
    <div class="tools">
        <button class="edit"><i class="fas fa-edit"></i></button>
        <button class="delete"><i class="fas fa-trash-alt"></i></button>  <!-- 修正图标类名 -->
    </div>
    <div class="main ${text ? '' : 'hidden'}">${text}</div>
    <textarea class="${text ? 'hidden' : ''}">${text}</textarea>
    `;

const editBtn = note.querySelector('.edit');  
const deleteBtn = note.querySelector('.delete'); 
const main = note.querySelector('.main');      
const textArea = note.querySelector('textarea'); 

deleteBtn.addEventListener('click', () => {         note.remove();
    updateLS();
});

editBtn.addEventListener('click', () => {
    main.classList.toggle('hidden');
   textArea.classList.toggle('hidden');
   textArea.focus();
});

textArea.addEventListener('input', (e) => {
    main.innerHTML = marked(e.target.value);  // 使用marked解析Markdown
    updateLS();  // 实时保存
});
    document.body.appendChild(note);
}

function updateLS() {
    const notesText = document.querySelectorAll('textarea');
    const notes = [];
    notesText.forEach(note => notes.push(note.value));
    localStorage.setItem('notes', JSON.stringify(notes));
}